﻿using System;
using System.Windows.Forms;
using Alerter.DataSet;
using DevExpress.XtraGrid.Views.Grid;

namespace Alerter.Controls
{
    public partial class MessageTypeListUserControl : UserControl, IList, IGridView
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.MessageTypeSaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public MessageTypeListUserControl()
        {
            InitializeComponent();
            gridView.DoubleClick += GridViewDoubleClick;
        }

        #region Private Methods

        private void SetGridDataSource()
        {
            TipoMensagemDataSet dataSet = _controller.GetMessageTypes();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.TipoMensagem.TableName;
        }

        private void ShowMessageType(long documentId)
        {
            var window = new MessageTypeXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
        }

        #endregion

        public void AddDocument()
        {
            ShowMessageType(-1);
        }

        public void DeleteDocument()
        {
            var document = (TipoMensagemDataSet.TipoMensagemRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (document == null)
                return;
            var result = MessageBox.Show(_controller.OwnerWindow, string.Format("'{0}' será eliminada definitivamente.", document.Nome),
                 "Tipo Mensagem", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if (result != DialogResult.OK)
                return;
            _controller.DeleteMessageType(document.Id);
        }


        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var messageType = (TipoMensagemDataSet.TipoMensagemRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (messageType == null)
                return;
            ShowMessageType(messageType.Id);
        }

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "MessageType"; }
        }
    }
}
